package com.ian.linked;


import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyaowen
 * @date 2021/2/21 4:02 下午
 */
public class TreeNode {

    public Integer val;

    public TreeNode left;

    public TreeNode right;

    public TreeNode(int i) {
        this.val = i;
    }

    public TreeNode() {
    }

    public void dfs(TreeNode node){

        if (node == null){
            return;
        }
        dfs(node.left);
        System.out.println(node.val);
        dfs(node.right);
    }


    public static TreeNode buildTreeNode(Integer[] arr){
        if (arr ==null ||arr.length ==0){
            return new TreeNode();
        }

        List<TreeNode> nodeList = new ArrayList<>(arr.length);
        for (Object val:arr) {
            TreeNode node = new TreeNode();
            node.val = (Integer) val;
            nodeList.add(node);
        }

        for (int i = 0; i < nodeList.size()/2 -1; i++) {
            TreeNode node = nodeList.get(i);
            node.left = nodeList.get(i*2+1);
            node.right = nodeList.get(i*2+2);
        }

        int last = nodeList.size()/2 -1;
        TreeNode lastNode = nodeList.get(last);

        lastNode.left = nodeList.get(last*2+1);
        if (nodeList.size()%2!=0){
            lastNode.right = nodeList.get(last*2+2);
        }

        return nodeList.get(0);
    }

}
